package com.pv.bfc.web.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.pv.bfc.model.BriefcaseUser;

public class UserValidator implements Validator {
	@SuppressWarnings("unchecked")
	public boolean supports(Class clazz) {
		return BriefcaseUser.class.isAssignableFrom(clazz);
	}

	public void validate(Object user, Errors errors) {

		BriefcaseUser bfcUser = (BriefcaseUser) user;
		final int MINIMUM_PASSWORD_LENGTH = 8;

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName",
				"error.required.user.uname");

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
				"error.required.user.fname");

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
				"error.required.user.lname");

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email",
				"error.required.user.email");

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
				"error.required.user.password");

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword",
				"error.required.user.confirmpassword");

		// Set the email pattern string
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(bfcUser.getEmail());
		boolean matchFound = m.matches();

		if ((bfcUser.getEmail() != null) && !matchFound) {
			errors.rejectValue("email", "error.required.user.email.invalid");
		}

		// Password Strength validation
		if (bfcUser.getPassword() != null
				&& bfcUser.getPassword().trim().length() < MINIMUM_PASSWORD_LENGTH) {
			errors.rejectValue("password",
					"error.required.user.password.length",
					new Object[] { Integer.valueOf(MINIMUM_PASSWORD_LENGTH) },
					"The password must be at least [" + MINIMUM_PASSWORD_LENGTH
							+ "] characters in length.");
		}

		if (bfcUser.getPassword() != null
				&& !bfcUser.getPassword().matches(
						"^(?=.*[A-Z])(?=.*\\d)(.{8,})$")) {
			errors
					.rejectValue("password",
							"error.required.user.password.strength",
							new Object[] { Integer
									.valueOf(MINIMUM_PASSWORD_LENGTH) },
							"The password must be at least one upper one lower characters.");
		}

		// Check for Confirm Password
		if (!(bfcUser.getPassword().equals(bfcUser.getConfirmPassword()))) {
			errors.rejectValue("confirmPassword",
					"error.required.user.notmatch.password");
		}
	}
}
